package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseOrderSaleDetailFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.OderSaleContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import java.util.HashMap;
import org.json.JSONException;

public class EditOrderSaleDeatilFragment extends BaseOrderSaleDetailFragment {
  public static final String EXTRA_CONTENT = "com.isunland.managesystem.entity.EXTRA_CONTENT";
  private OderSaleContent mContent;

  @Override public void onCreate(Bundle savedInstanceState) {
    mContent = (OderSaleContent) getArguments().getSerializable(EXTRA_CONTENT);
    if (mContent != null) {
      customerId = mContent.getMcustomerId();
      materialKindCode = mContent.getMaterialKindCode();
      warehouseId = mContent.getStorageId();
      salePersonId = mContent.getMoutappmanId();
    }

    super.onCreate(savedInstanceState);
  }

  @Override protected void setTitle() {
    BaseVolleyActivity activity = ((BaseVolleyActivity) getActivity());
    if (activity.getSupportActionBar() != null) {
      activity.getSupportActionBar().setTitle(R.string.order_detail);
    }
  }

  @Override protected void initOrderData() {
    tvCustomerCompany.setText(mContent.getMcustomerName());
    etCustomerApartment.setText(mContent.getMcustomerDeptName());
    etMainProduct.setText(mContent.getMoutCom());
    tvMaterialKind.setText(mContent.getMaterialKindName());//出库物料类别
    tvWarehouse.setText(mContent.getStorageName());//出货仓库
    tvSalePerson.setText(mContent.getMoutappmanName());//销售业务员
    tvOutNotes.setText(mContent.getMoutbillNo());//出库单编号
    tvRegisteredErson.setText(mContent.getRegStaffName());//登记人
    tvRegisteredTime.setText(mContent.getRegDate());//登记时间
    if ("new".equals(mContent.getMoutbillStatus())) {
      tvDataStatus.setText(R.string.draft);//数据状态
    } else if ("checkPass".equals(mContent.getMoutbillStatus())) {
      tvDataStatus.setText(R.string.already_submit);//数据状态
    } else if ("outStock".equals(mContent.getMoutbillStatus())) {
      tvDataStatus.setText(R.string.already_out);//数据状态
    }
    //		else {
    //			tvDataStatus.setText("全部");//数据状态
    //		}

    tvHandlePrson.setText(mContent.getMoutdealmanName());//办理人
    tvHandleTime.setText(mContent.getMoutdealDate());//办理时间
    etNotes.setText(mContent.getRemark());//备注
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.menu_confirm, menu);

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_confirm:
        //修改保存订单详情
        //			volleyPostSave();
        showDialog(SAVE_ORDER);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  //保存订单明细
  private void volleyPostSave() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SAVE_ORDER);

    mContent.setMcustomerName(tvCustomerCompany.getText().toString());
    mContent.setMcustomerId(customerId);

    mContent.setMcustomerDeptName(etCustomerApartment.getText().toString());
    mContent.setMoutCom(etMainProduct.getText().toString());

    mContent.setMaterialKindCode(materialKindCode);
    mContent.setMaterialKindName(tvMaterialKind.getText().toString());

    mContent.setStorageName(tvWarehouse.getText().toString());
    mContent.setStorageId(warehouseId);

    mContent.setMoutappmanName(tvSalePerson.getText().toString());
    mContent.setMoutappmanId(salePersonId);

    mContent.setRemark(etNotes.getText().toString());
    //登记人登记时间
    mContent.setRegStaffName(mCurrentUser.getRealName());
    mContent.setRegStaffId(mCurrentUser.getJobNumber());

    HashMap<String, String> mparams = new HashMap<>();
    mparams.put("updated", "[" + new Gson().toJson(mContent) + "]");
    LogUtil.i("修改参数mparams====" + mparams.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, mparams, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == SAVE_ORDER) {
      //修改保存订单详情
      volleyPostSave();
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  public static EditOrderSaleDeatilFragment newInstance(OderSaleContent item) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, item);
    EditOrderSaleDeatilFragment fragment = new EditOrderSaleDeatilFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
